<template>
  <div v-loading="loading"
       element-loading-text="正在提交..."
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-input style="margin-bottom: 20px;" v-model="title" placeholder="标题"/>
    <div id="editor" ref="editor" style="text-align:left"></div>
    <el-button type="primary" @click="addArticle" class="input_sub">提交</el-button>
  </div>
</template>
<script>

import E from 'wangeditor'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'

export default {
  name: 'ArticleEditor',
  props: ["tagId"],
  data(){
    return{
      editor:'',
      editorData: '',
      title: '',
      loading: false
    }
  },
  methods:{
    addArticle() {
      let param={
        userId : JSON.parse(sessionStorage.getItem("user")).id,
        title : this.title,
        content : this.editorData,
        tagId : this.tagId
      }

      if (param.userId == null) {
        this.$message.error("请登录")
        return;
      }

      if (param.title == null || param.title === '') {
        this.$message.error("请输入标题")
        return;
      }

      if (param.tagId == null) {
        this.$message.error("请选择板块")
        return;
      }

      if (param.content == null || param.content === '') {
        this.$message.error("请输入内容")
        return;
      }

      this.loading = true;
      this.postRequest('article/',param).then(()=>{
        this.editor.txt.clear()
        this.title = ''
      })
      this.loading = false;
      this.$emit("loadArticles",this.tagId)
    }
  },
  mounted() {
    let editor= new E(this.$refs.editor);
    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = (newHtml) => {
      this.editorData = newHtml
    }

    let OSS = require('ali-oss');
    let client = new OSS({
      // // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
       region: 'oss-cn-chengdu',
      // // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
       accessKeyId: 'LTAI5t9sghDws12ZRY1ZNmLv',
       accessKeySecret: 'rXnZ7zEmLx0oREp1HbtS2KsHoLKxuO',
       bucket: 'topforum-oss',
    });

    editor.config.customUploadImg = function (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      client.put('article_img/'+Date.now()+".jpg", resultFiles[0])
          .then(function (res) {
            // 上传图片，返回结果，将图片插入到编辑器中
            insertImgFn(res.url)
          }).catch(function (err) {
        console.log(err)
      })
    }
    editor.config.zIndex = 500
    editor.config.placeholder = '帖子内容'
    editor.highlight = hljs
    editor.config.uploadImgMaxLength = 5
    let val = this
    editor.config.customAlert =  (s, t) => {

      switch (t) {
        case 'success':
          val.$message.success(s)
          break
        case 'info':
          val.$message.info(s)
          break
        case 'warning':
          val.$message.warning(s)
          break
        case 'error':
          val.$message.error(s)
          break
        default:
          val.$message.info(s)
          break
      }
    }
    editor.create()
    this.editor = editor
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    this.editor = null
  }
}
</script>
